<template>
  <view class="categorys">
    <up-status-bar></up-status-bar>


    <!-- 搜索框 -->
    <view class="input-view">
      <!-- <view class="city">{{ data.city }}</view> -->
      <view class="input-view-box">
        <view class="input_viewbox">
          <uni-icons color="#00C356" type="search" size="20"></uni-icons>
          <input v-model="data.keywordList" @input="sherList" placeholder='请输入商品名称'/>
        </view>
      </view>

    </view>
    <view class="type_cnt">
      <scroll-view class="bg" scroll-x="true" :scroll-top="data.scrollTop" :scroll-with-animation="true">
        <view class="type_x_cnt l_f_r">
          <view v-for="(item,index) in shoplist" class="nav-item text_5_28" :class="{'ac':data.active == index}"
                @click="changeNav(index,item.ID)">
            <view>{{ item.name }}</view>
            <view class="line_" v-if="data.active==index"></view>
          </view>
        </view>

      </scroll-view>
    </view>
    <empty v-if="data.shopsecond.length==0"></empty>
    <view class="shopList">
      <template v-for="(item,index) in data.shopsecond">
        <view class="item" @click="$goURl(`/subPackages/commodity/details?id=${item.ID}`)">
          <view class="img_cnt">
            <image class="img" :src="item.img" mode="aspectFill">
            </image>
          </view>
          <view class="name text_5_28 ">
            {{ item.name }}
          </view>
          <view class="l_f_r_sb_c mun_cnt ">
            <view class="">
              <view  class="price text_b_36" v-if="item.price>0">
                <text class="text_b_20">￥</text>{{ $toFiexd(item.price, 2) }}
              </view>
              <text v-if="item.price==0 &&item.coupon>0 " style="font-size: 15px;">
                <text style="font-size: 13px;">积分</text>
                :{{ item.coupon }}
              </text>
            </view>
<!--            <view class="ductdrowb" @click.stop="bindChange(item,index,1)">-->
<!--              <uni-icons type="plusempty" color="#fff" size="13"></uni-icons>-->
<!--            </view>-->
          </view>
        </view>
      </template>
        <view style="width: 100%;height: 30px;margin-bottom: 50px;"></view>

    </view>
    <!-- 左右联动 -->
    <!--			<view class="category">-->
    <!--				<view class="nav">-->
    <!--					<scroll-view class="bg" scroll-y="true" :scroll-top="data.scrollTop" :scroll-with-animation="true"-->
    <!--						:style="{height: data.screenWith + 'px'}">-->
    <!--						<block v-for="(item,index) in shoplist" :key="index">-->
    <!--							<view class="nav-item" :class="{'ac':data.active == index}"-->
    <!--								@click="changeNav(index,item.ID)">-->
    <!--								<text>{{item.name}}</text>-->
    <!--							</view>-->
    <!--						</block>-->
    <!--					</scroll-view>-->
    <!--				</view>-->
    <!--				<view class="goodsBox" v-if="shoplist[data.active].arr || data.active == 0">-->
    <!--					&lt;!&ndash; <view>-->
    <!--						<image src="https://pili-vod.guanxikeji.com/houdejia/img/1710467040708.png"-->
    <!--							style="width: 100%;height: 80px;"></image>-->
    <!--					</view> &ndash;&gt;-->
    <!--					<view class="second">-->
    <!--						<scroll-view scroll-x="true" style="white-space: nowrap;">-->
    <!--							<text class="back" v-for="(min,indexs) in shoplist[data.active].arr" :key="indexs"-->
    <!--								@click="second(min.ID)" :class="data.secondID==min.ID?'linbei':''">{{min.name}}</text>-->
    <!--						</scroll-view>-->
    <!--					</view>-->
    <!--					<view>-->
    <!--						<view class="emipt">-->
    <!--							<view class="sort_b">-->
    <!--								<view class="screenItem" @click="setSort(0)">-->
    <!--									综合-->
    <!--									&lt;!&ndash; <screen :type="data.sort == 1 ? 1 : data.sort == 2 ? 2 : 0"></screen> &ndash;&gt;-->
    <!--								</view>-->
    <!--								<view class="screenItem" @click="setSort(1)">-->
    <!--									销量-->
    <!--									<screen :type="data.sort == 1 ? 1 : data.sort == 2 ? 2 : 0"></screen>-->
    <!--								</view>-->
    <!--								<view class="screenItem" @click="setSort(2)">-->
    <!--									价格-->
    <!--									<screen :type="data.sort == 3 ? 1 : data.sort == 4 ? 2 : 0"></screen>-->
    <!--								</view>-->

    <!--							</view>-->
    <!--						</view>-->
    <!--						<scroll-view scroll-y="true" :style="{height: data.screenWith + 'px'}"-->
    <!--							@scrolltolower='scrolltolower'>-->
    <!--							<empty v-if="data.shopsecond.length==0"></empty>-->
    <!--							<BJL-waterfall scrollHeight="50%" :data="data.shopsecond"-->
    <!--								styleData="{backgroundColor: '#e7e7e7'}">-->
    <!--								<template #scrollItem="{ item , index }">-->
    <!--									<view class="item">-->
    <!--										<view class="ductarow">-->
    <!--											<image class="" :src="item.img" mode="widthFix"-->
    <!--												@click="$goURl(`/subPackages/commodity/details?id=${item.ID}`)">-->
    <!--											</image>-->
    <!--										</view>-->
    <!--										<view class="ductbrow textsl2"-->
    <!--											@click="$goURl(`/subPackages/commodity/details?id=${item.ID}`)">-->
    <!--											{{item.name}}-->
    <!--										</view>-->
    <!--										<view class="ductdrow box_db">-->
    <!--											<view class="ductdrowa"-->
    <!--												@click="$goURl(`/subPackages/commodity/details?id=${item.ID}`)">-->
    <!--												<text v-if="item.price>0">-->
    <!--													￥{{$toFiexd(item.price,2)}}-->
    <!--												</text>-->
    <!--												<text v-if="item.price==0 &&item.coupon>0 " style="font-size: 15px;">-->
    <!--													<text style="font-size: 13px;">积分</text>:{{item.coupon}}-->
    <!--												</text>-->
    <!--											</view>-->
    <!--											<view class="ductdrowb" @click="bindChange(item,index,1)">-->
    <!--												<uni-icons type="plusempty" color="#fff" size="13"></uni-icons>-->
    <!--											</view>-->
    <!--										</view>-->
    <!--									</view>-->
    <!--								</template>-->
    <!--								<template #bottom>-->
    <!--									<view style="width: 100%;height: 30px;margin-bottom: 50px;"></view>-->
    <!--								</template>-->
    <!--							</BJL-waterfall>-->
    <!--						</scroll-view>-->
    <!--					</view>-->
    <!--				</view>-->
    <!--			</view>-->

    <!-- 立即购买弹窗 -->
  </view>
</template>

<script setup>
import screen from "@/components/screen/screen.vue"
import {
  ref,
  reactive,
  getCurrentInstance
} from "vue";
import {
  onLoad,
  onShow,
  onReachBottom
} from "@dcloudio/uni-app";

const {
  appContext
} = getCurrentInstance();
const data = reactive({
  active: 0,
  scrollTop: 0,
  height: 0,
  shoplist: [],
  // 分类列表子集
  shoplistDe: [],
  shopsecond: [],
  secondID: -1,
  dataID: 1,
  isShow: false, //是否显示规格蒙版
  goods: {},
  lists: [], //规格
  goodsdetali: {},
  listckeck: [],
  listckecks: [],
  selectlist: [],
  speci: 0, //规格ID
  number: 1, //数量
  page: 0,
  pages: 1,
  size: 10,
  screenWith: '', //屏幕高度
  keywordList: '', //搜索信息
  sort: 2, //排序
})
let shoplist = ref([])
const popup = ref()
onLoad((opt) => {
  // data.shoplistDe = data.shoplist[0].child
  secondary()
})
onShow(() => {
  // 业务逻辑
  uni.getSystemInfo({
    success: function (res) {
      console.log(res);
      if (res.platform == 'ios') {
        if (res.windowBottom > 0) {
          data.screenWith = res.windowHeight - 94
        } else {
          data.screenWith = res.windowHeight - 144
        }
      } else {
        if (res.windowBottom > 0) {
          data.screenWith = res.windowHeight - 80
        } else {
          data.screenWith = res.windowHeight - 130
        }
      }
    }
  });
})
const scrolltolower = () => {
  getdatas()
}
const buttonClick = (e) => {
  popup.value.open('bottom')
}

// 点击加入购物车
function create() {

}

const ckeck = (a, b) => { //规格选择
  console.log("选择完成", data.listckeck)
  data.listckeck[a] = b
  // console.log("选择完成", data.listckeck,data.lists)
  let num = data.listckeck.filter(item => {
    return item >= 0
  }).length

  if (num == data.lists.length) {
    let attribute = ''
    data.listckeck.forEach((item, index) => {
      if (index < data.lists.length) {
        attribute = attribute + data.lists[index].id[item] + (index < data.lists.length - 1 ? '|' :
            '')
      }
    })
    let listsss = []
    data.lists.forEach((item, index) => {
      listsss.push(item.ID[data.listckeck[index]])
    })
    data.speci = listsss[0]
    data.listckecks = listsss
    data.attribute = attribute
    let goodsNmae = data.goods.name
    data.goods = data.goodsdetali.attribute_list.filter(item => {
      return item.attribute == attribute
    }).map(item => {

      // data.speci = item.attr[0].ID
      return {
        img: item.img,
        coupon: item.coupon,
        price: item.price,
        stock: item.stock,
        ID: item.ID,
        name: goodsNmae
      }
    })[0]

  }
}
// 关闭弹窗
const close = () => {
  popup.value.close()
}

function goURl() {
  uni.navigateBack()
}

//排序
function setSort(index) {
  if (index == 0 && data.sort != 0) {
    data.sort = index
  } else if (index == 1 && (data.sort < 1 || data.sort > 2)) {
    data.sort = 1
  } else if (index == 1) {
    if (data.sort == 1) {
      data.sort = 2
    } else {
      data.sort = 1
    }
  } else if (index == 2 && (data.sort < 3)) {
    data.sort = 3
  } else if (index == 2) {
    if (data.sort == 3) {
      data.sort = 4
    } else {
      data.sort = 3
    }
  }
  sherList()
}

// 点击加入购物车图片
function bindChange(item, index, e) {
  data.listckeck = [0]
  appContext.config.globalProperties.$request({
    url: `api/goods_list_all/0/`,
    method: 'POST',
    data: {
      id: item.ID
    },
    success: (res) => {
      if (res.errno == 0) {
        data.speci = res.data.attribute_list[0].ID
        if (res.data.attribute_list.length != 1) {
          popup.value.open('bottom')
          data.number = 1

        } else {
          data.number = 1
          shoppingCart(res.data.attribute_list[0].ID)
        }
        data.lists = arr(res.data.attribute_list)
        console.log(data.lists, "data.lists")
        data.goodsdetali = res.data
        data.goods = {
          img: res.data.img,
          price: res.data.price,
          stock: res.data.stock,
          coupon: res.data.coupon,
          ID: res.data.attribute_list[0].ID,
          name: res.data.name,
        }
      }
    }
  })
}

// 规格排列组合
const arr = (arr) => {
  var list = []
  arr[0]['attr'].forEach(f => {
    // console.log()
    list.push({
      attr: f.attr,
      val: [],
      id: [],
      ID: []
    })
    // data.listckeck.push(0)
  })
  arr.forEach(f => {
    f.attr.forEach(t => {
      for (var k = 0; k < list.length; k++) {
        if (list[k].attr == t.attr) {
          list[k].val.push(t.val)
          list[k].id.push(t.ID)
          list[k].ID.push(f.ID)
        }
      }
    })
  })
  for (var i = 0; i < list.length; i++) {
    list[i].val = [...new Set(list[i].val)]
    var s = []
    for (var k = 0; k < list[i].val.length; k++) {
      s.push(k == 0 ? 1 : 0)
    }
    data.selectlist.push(s)
  }
  list.forEach(item => {
    item.id = Array.from(new Set(item.id))
  })
  return list
}

function shoppingCart(id) {
  let imd = ''
  if (typeof (id) != 'object') {
    imd = id
  } else {
    imd = data.speci
  }
  appContext.config.globalProperties.$request({
    url: `api/shoppingCart/`,
    method: 'POST',
    data: {
      attribute_id: imd,
      number: data.number
    },
    success: (res) => {
      if (res.errno == 0) {
        uni.showToast({
          icon: 'none',
          title: '加入购物车成功'
        })
        popup.value.close()
      } else {
        uni.showToast({
          icon: 'none',
          title: res.errmsg
        })
      }

    }
  })
}

// 搜索
function sherList(e) {
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  getdatas()
}

// 点击搜索
function shoer() {
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  data.secondID = -1
  getdatas()
}

// 点击二级分类
function second(id) {
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  data.secondID = id
  getdatas()
}

// 获取数据
function getdatas() {
  if (data.page < data.pages) {
    data.page++
    let datas = []
    appContext.config.globalProperties.$request({
      url: `api/goods_list_all/${data.dataID}/?class_second_id=${data.secondID}&page=${data.page}&size=${data.size}&keyword=${data.keywordList}&sort=${data.sort}&is_single=0`,
      method: 'GET',
      success: (res) => {
        datas = res.data.data
        console.log("res", res)
        if (res.errno == 0) {
          data.shopsecond = [...data.shopsecond, ...datas]
          data.pages = Math.ceil(res.data.total / data.size)
        } else {
          uni.showToast({
            icon: 'none',
            title: res.errmsg
          })
          data.shopsecond = []

        }
        console.log("data.shopsecond", data.shopsecond)
      }
    })
  }
}

// 商品分类
function secondary() {
  appContext.config.globalProperties.$request({
    url: `api/typeList/`,
    method: 'GET',
    success: (res) => {
      if (res.errno == 0) {
        data.dataID = 0
        let datae = res.data.class_first
        let datas = res.data.class_second

        shoplist.value = []
        datae.forEach((item, index) => {
          shoplist.value.push({
            name: item.name,
            ID: item.ID,
            arr: [{
              name: '全部',
              ID: -1,
            }],
          })

          datas.forEach((items, indexs) => {
            if (item.ID == items.class_first_id) {
              shoplist.value[index].arr.push({
                name: items.name,
                ID: items.ID,
              })
            }
          })
        })
        getdatas()
        shoplist.value.unshift({
          name: '全部',
          ID: 0,
        })
      }

    }
  })
}

function changeNav(index, id) {
  data.secondID = -1
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  data.dataID = id
  data.active = index;
  data.scrollTop = data.height * (index - 2);
  // if (data.screenWith > 624) {
  // 	data.screenWith = data.screenWith - 44
  // }
  getdatas(0, 0)
  // 在这里请求接口 展示右侧商品数据
  // data.shoplistDe = data.shoplist[index].child
}

function cat() {
  uni.navigateTo({
    url: '/pages/cat/cat' // 需要跳转的tab页面路径
  });

}
</script>

<style scoped lang="scss">
$nav-height: 30px;
$paddings: 10px;

page {
  background-color: #f6f6f6;

}

.categorys {
  height: calc(100vh - 50px);
  background-image: url("https://img.clc1319.com/static/img/category/topBG.png");
  background-size: 100% auto;
  background-repeat: no-repeat;
  padding-top: 1rpx;
}

.input-view {
  flex-direction: row;
  flex: 1;
  justify-content: center;
  height: 70upx;
  flex-wrap: nowrap;
  padding: $padding;
  overflow: hidden;
  display: flex;
  justify-content: left;
  align-items: center;
  margin-top: 34rpx;


  .cate {
    width: 15%;
    display: flex;
    align-items: center;
    flex-direction: column;
  }

  .input-view-box {
    width: 690rpx;
    margin: 0 auto;

    .input_viewbox {
      width: 100%;
      height: 70rpx;
      background: #FFFFFF;
      border: 2rpx solid #2E7D32;
      display: flex;
      // justify-content: space-between;
      align-items: center;
      border-radius: 62rpx;

      .uni-icons {
        margin: 0 20rpx;
      }
    }

    uni-input {
      height: 38px;
      line-height: 72upx;
      width: 80%;
      font-size: 16px;
      color: #9f9f9f;
    }


  }

}

.type_cnt {
  width: 690rpx;
  margin: 0 auto 20rpx;
  //overflow: hidden;

  .type_x_cnt {
    gap: 0 40rpx;
    height: 70rpx;

    .nav-item {
      position: relative;
      height: 30rpx;

      &.ac {
        font-weight: bold;
        font-size: 32rpx;
      }

      .line_ {
        position: absolute;
        width: 100%;
        left: 0;
        bottom: -20rpx;
        height: 2rpx;
        background: #2E7D32;
      }
    }
  }
}

.shopList {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 24rpx 18rpx;
  padding:0 30rpx;
  box-sizing: border-box;

  .item {
    width: 336rpx;
    height: 518rpx;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    background-color: #fff;

    .img_cnt {
      width: 336rpx;
      height: 336rpx;
    }
    .name{
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      min-height: 74rpx;
      margin: 20rpx 12rpx 20rpx;
    }
    .mun_cnt{
      margin: 0 12rpx;
    }
    .price,.text_b_20{
      color: #2E7D32 ;
    }
    .ductdrowb {
      width: 36rpx;
      height: 36rpx;
      background: #2E7D32;
      border-radius: 14rpx 14rpx 14rpx 14rpx;
      font-size: 28rpx;
      color: #FFFFFF;
      display: flex;
      justify-content: center;
      align-items: center;

    }
  }
}

</style>
